#define  _CRT_SECURE_NO_WARNINGS
#include "Tree.h"
#include "Queue.h"

BTNode* BuyNewNode(BTDatatype x)
{
	BTNode* newnode = (BTNode*)malloc(sizeof(BTNode));
	assert(newnode);
	newnode->data = x;
	newnode->Left = newnode->Right = NULL;
	return newnode;
}

void PreOrder(BTNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	printf("%d ", root->data);
	PreOrder(root->Left);
	PreOrder(root->Right);
}

void InOrder(BTNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	InOrder(root->Left);
	printf("%d ", root->data);
	InOrder(root->Right);
}

void PostOrder(BTNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	PostOrder(root->Left);
	PostOrder(root->Right);
	printf("%d ", root->data);
}

int BinaryTreeSize(BTNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	return 1 + BinaryTreeSize(root->Left) + BinaryTreeSize(root->Right);
}

int BinaryTreeLeafSize(BTNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	if (root->Left == NULL && root->Right == NULL)
	{
		return 1;
	}
	return BinaryTreeLeafSize(root->Left) + BinaryTreeLeafSize(root->Right);
}

int BinaryTreeLevelKSize(BTNode* root, int k)
{
	if (root == NULL)
	{
		return 0;
	}
	if (k == 1)
	{
		return 1;
	}
	return BinaryTreeLevelKSize(root->Left, k - 1) + BinaryTreeLevelKSize(root->Right, k - 1);
}

int BinaryTreeDepth(BTNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	int leftdep = BinaryTreeDepth(root->Left);
	int rightdep = BinaryTreeDepth(root->Right);
	
	return leftdep >= rightdep ? 1 + leftdep : 1 + rightdep;

}

BTNode* BinaryTreeFind(BTNode* root, BTDatatype x)
{
	if (NULL == root)
	{
		return NULL;
	}
	if (root->data == x)
	{
		return root;
	}
	BTNode* leftfind = BinaryTreeFind(root->Left, x);
	if (leftfind)
	{
		return leftfind;
	}
	BTNode* rightfind = BinaryTreeFind(root->Right, x);
	if (rightfind)
	{
		return rightfind;
	}
	return NULL;
}

void BinaryTreeDestory(BTNode** root)
{
	if (NULL == *root)
	{
		return;
	}
	BinaryTreeDestory(&((*root)->Left));
	BinaryTreeDestory(&((*root)->Right));

	free(*root);
	*root = NULL;
}

void LevelOrderr(BTNode* root)
{
	Queue s;
	QueueInit(&s);
	QueuePush(&s, root);
	while (!QEmpty(&s))
	{
		QDatatype front = QueueFront(&s);
		printf("%d->", front->data);
		QueuePop(&s);
		if (front->Left)
		{
			QueuePush(&s, front->Left);
		}
		if (front->Right)
		{
			QueuePush(&s, front->Right);
		}
	}
	
}

bool BinaryTreeComplete(BTNode* root)
{
	Queue s;
	QueueInit(&s);

	QueuePush(&s, root);
	
	while (!QEmpty(&s))
	{
		QDatatype front = QueueFront(&s);
		
		if (front == NULL)
		{
			break;
		}
		QueuePop(&s);
		QueuePush(&s, front->Left);
		QueuePush(&s, front->Right);
	
	}
	while (!QEmpty(&s))
	{

		QDatatype front = QueueFront(&s);
		QueuePop(&s);
		if (front != NULL)
		{
			QueueDestroy(&s);
			return false;
		}

	}
	QueueDestroy(&s);
	return true;
}